<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--企业数据-->
      <el-col :span="4" :xs="24" v-show="false">
        <div class="head-container">
          <el-input
            v-model="dept_name"
            placeholder="请输入企业名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />

        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            @node-click="handleNodeClick"
            default-expand-all
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="mainwidth" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="账单日期">

            <el-date-picker
              v-model="queryParams.month"
              type="month"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-form>

        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px" style="margin-bottom: -10px;line-height:35px">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-form-item label="企业名称" prop="dname" style="margin-bottom: 10px;line-height:35px">
                <el-input
                  v-model="queryParams.dname"
                  placeholder="请输入完整企业名称"
                  clearable
                  size="small"
                  style="width: 240px"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
                v-hasPermi="['yunze:bill:list']"
              >导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
          </el-row>
        </el-form>



        <el-table v-loading="loading" :data="billList" @selection-change="handleSelectionChange"
                  row-key="id"
                  :expand-row-keys="expandKeys"
                  @expand-change="expandChange"
                  @row-click = "expandChange"

        >
          <el-table-column type="expand" width="50" align="center"  >

            <template slot-scope="scope" >
              <el-table v-loading="plistshwo" :data="scope.row.plist" :load="expandChange">
                  <el-table-column  width="50" align="center" />
                  <el-table-column label="资费计划" align="center" key="packet_id" prop="packet_id"  />
                  <el-table-column label="卡总数" align="center" key="count" prop="count"  />
                  <el-table-column label="本月激活" align="center" key="activecount" prop="activecount"  />
                  <el-table-column label="停机数量" align="center" key="haltcount" prop="haltcount"  />
                  <el-table-column label="本月用量" align="center" key="used" prop="used"  />
                  <el-table-column label="剩余用量" align="center" key="remaining" prop="remaining"  />
                  <el-table-column label="时间" align="center" key="month" prop="month"  />
              </el-table>
            </template>>

          </el-table-column>>
          <el-table-column label="企业名称" align="center" key="dept_name" prop="dept_name" v-if="columns[0].visible" />
          <el-table-column label="卡总数" align="center" key="count" prop="count" v-if="columns[0].visible" />
          <el-table-column label="当月激活数量" align="center" key="active_count" prop="active_count" v-if="columns[1].visible"  />
          <el-table-column label="待激活数量" align="center" key="not_active_count" prop="not_active_count" v-if="columns[2].visible" />
          <el-table-column label="当月用量" align="center" key="used" prop="used" v-if="columns[3].visible"  />
          <el-table-column label="当月剩余用量" align="center" key="remaining" prop="remaining" v-if="columns[4].visible" width="120" />
          <el-table-column label="停机数量" align="center" key="halt_count" prop="halt_count" v-if="columns[5].visible" width="120" />
          <el-table-column label="账单时间" align="center" key="month" prop="month" v-if="columns[6].visible" width="120" />
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>







  </div>
</template>

<script>
import { listUser, getUser, exportUser } from "@/api/yunze/user/agent";
import {getList,exportBill,getPlist} from "@/api/yunze/bill/bill"
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import tools from "@/utils/yunze/tools";

export default {
  name: "agent",
  components: { Treeselect },
  data() {
    return {

      expandKeys:[],
      tableData: [],
      Planform: {},
      showPlan_ds: false,//划分 资费计划
      mainwidth:24,//宽度
      tools:tools,
      tariffPlanList:[],//划分资费计划 List
      packageOptions:[],//资费组
      customize_whether: [],//自定义是否
      error_flowShow:false,//是否显示 已经划分 设置好的用量

      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },

      selTime:'',//时间选择


      plistshwo:true,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 账单数据
      billList:null,
      // 弹出层标题
      title: "",
      // 企业树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 企业名称
      dept_name: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      // 性别状态字典
      sexOptions: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [
        {
          roleName:'企业客户',
          roleId:2,
        },
        {
          roleName:'用户',
          roleId:4,
        }
      ],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        month:null,
        dname:null
      },
      // 列信息
      columns: [
        { key: 0, label: `企业名称`, visible: true },
        { key: 1, label: `当月激活数量`, visible: true },
        { key: 2, label: `待激活数量`, visible: true },
        { key: 3, label: `当月用量`, visible: true },
        { key: 4, label: `当月剩余用量`, visible: true },
        { key: 5, label: `停机数量`, visible: true },
        { key: 6, label: `账单时间`, visible: true }
      ],

    };
  },
  watch: {
    // 根据名称筛选企业树
    dept_name(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getTreeselect();
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_user_sex").then(response => {
      this.sexOptions = response.data;
    });
    this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg;
    });

    //加载 自定义 是否 0 1 否 是
    if(window['customize_whether']!=undefined &&  window['customize_whether']!=null && window['customize_whether']!=''){
      this.customize_whether = window['customize_whether'];
    }else{
      this.getDicts("yunze_customize_whether").then(response => {
        window['customize_whether'] = response.data;
        this.customize_whether = window['customize_whether'];
      });
    }

  },

  methods: {
    expandChange(row,expandRows){

      if (row.plist == null){
        let Pwd_Str = tools.encrypt(JSON.stringify(row.id));
        getPlist(Pwd_Str).then(res=>{
          let jsonobj =  JSON.parse(tools.Decrypt(res));
          console.log(jsonobj.Data)
          this.$root.$set(row,"plist",jsonobj.Data.data)
          //row.plist = jsonobj.Data.data;
          //this.expandChange(row,expandRows)
        })
      }
      this.plistshwo = false;

    },

    /*获取查询参数*/
    getParams(){

    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      this.getParams();
      let Pwd_Str = tools.encrypt(JSON.stringify(this.queryParams));
      //console.log(Pwd_Str);
      getList(Pwd_Str).then(response => {
          let jsonobj =  JSON.parse(tools.Decrypt(response));
          //console.log(jsonobj);
          if(jsonobj.code==200){
            this.billList = jsonobj.Data.Data;
            this.total = jsonobj.Data.Pu.rowCount;
          }else{
            this.msgError(jsonobj.msg);
          }
          this.loading = false;
        }
      );
    },
    /** 查询企业下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.getList();
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        month: undefined,
        dname: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.month =undefined;
      this.queryParams.dname = undefined;
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.user_id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      const user_id = row.user_id || this.ids;
      getUser(user_id).then(response => {
        // console.log(response.roleIds)
        this.form = response.data;
        this.postOptions = response.posts;
        //this.roleOptions = response.roles;
        this.form.postIds = response.postIds;
        this.form.roleIds = response.roleIds;
        this.open = true;
        this.title = "修改用户";
        this.form.password = "";
      });
    },




    /** 导出按钮操作 */
    handleExport() {
      //console.log(this.queryParams)
      this.loading = true;
      this.getParams();
      let Pwd_Str = tools.encrypt(JSON.stringify(this.queryParams));
      exportBill(Pwd_Str).then(res=>{
        let jsonobj =  JSON.parse(tools.Decrypt(res));
        //console.log(jsonobj)
        if(jsonobj.code == 200){
          this.msgSuccess(jsonobj.Data);
          this.loading = false;

        }else{
          //失败
          this.msgError(jsonobj.msg);
          this.loading = false;
        }
      })
    },



  }
};
</script>
